var api = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        SomethingTapped: !1,
        animationData: {},
        addPanelTop: null,
        addPanelBottom: null,
        curIndex: -1,
        ed_para_list: '',
        paraList: [],
        edArticle_wy: ''
    },
    dataList: {                 //完成时存放的所有数据
        titleList: '',          //标题
        music: {                //音乐的数据
            music_id: '',
            music_name: '',
            music_url: ''
        },
        coverImg: [],           //封面图的数据
        contents: [],
        uid: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.dataList.uid = wx.getStorageSync('userData').u_id
        if (options.temp_file_paths){
            this.upload_img(options.temp_file_paths);
        }
        if (options.text){
            this.add_title(options.text)
        }
        if (options.video_file_path){
            this.upload_video(options.video_file_path, 0);
        }
        // 编辑
        if (options.a_id){
            this.data.edArticle_wy = options.edArticle_wy
            this.articleEdit(options.a_id);
        }
        this.dpr = wx.getSystemInfoSync().screenWidth / 750;
        
    },
    articleEdit: function (articleId){
        var a = this, u = wx.getStorageSync('userData').u_id;
        wx.showLoading({ title: '玩命加载中...'});
        wx.request({
            url: api.globalData.Api + '/articleEdit',
            method: 'GET',
            data: {
                articleId: articleId 
            },
            dataType:'json',
            success(res){
                if(res.data.status == 1){
                    var s = res.data.data;
                    a.dataList = s, a.dataList.uid = u;
                    a.setData({
                        title: s.titleList,         //  标题
                        music_name: s.musicName,    //  音乐名称
                        coverImg: s.coverImg[0],    //  封面图
                        paraList: s.contents        // contents列表
                    }), wx.hideLoading();
                }
            }
        })
    },

    upload_img: function (temp_file_paths, contents_list_id){
        var a = this, d = a.dataList.contents;
        if (temp_file_paths) {
            var p = JSON.parse(temp_file_paths);
            wx.showLoading({
                title: "正在上传图片",
                mask: !0
            })
            for (let i = 0; i < p.length; i++) {
                wx.uploadFile({
                    url: api.globalData.Api + '/uploadImg',
                    filePath: p[i],
                    name: "file",
                    header: { "Content-Type": "multipart/form-data" },
                    success(res) {
                        var j = JSON.parse(res.data), obj = new Object();
                        obj.conImg = j.data; obj.conText = ''; obj.conVideoUrl = '';
                        d.splice(contents_list_id + 1, 0, obj);
                        if (a.dataList.coverImg.length == 0){
                            a.dataList.coverImg[0] = j.data;
                            a.setData({
                                paraList: d,
                                coverImg: a.dataList.coverImg[0]
                            }), wx.hideLoading();
                        }else{
                            a.setData({
                                paraList: d,
                            }), wx.hideLoading();
                        }
                    }
                })
            }
        }
    },
    upload_video: function (video_file_path, contents_list_id){
        var a = this, d = a.dataList.contents;
        if (video_file_path) {
            var v = JSON.parse(video_file_path);
            wx.showLoading({
                title: "正在上传视频",
                mask: !0
            })
            wx.uploadFile({
                url: api.globalData.Api + '/uploadVideo',
                filePath: v,
                name: "file",
                header: api.header,
                success(res) {
                    var j = JSON.parse(res.data), obj = new Object();
                    if (j.status == 1){
                        obj.conImg = j.data.imgUrl; obj.conText = '';
                        obj.conVideoUrl = j.data.url;
                        d.splice(contents_list_id + 1, 0, obj);
                        a.setData({ paraList: d }), wx.hideLoading();
                    }else{
                        console.log('视频上传失败');
                    }
                },
                fail(res){
                    console.log(res,'接口调用失败');
                }
            })
        }
    },

    add_title: function(text, id){
        var obj = new Object(), d = this.dataList.contents, c = this.data.curIndex, n = this.data.ed_para_list;
        var p = this.data.paraList[n];
        if(id == -2){
            obj.conImg = p.conImg; obj.conText = text; obj.conVideoUrl = p.conVideoUrl;
            d.splice(n, 1, obj);
            this.setData({ paraList: d }), wx.hideLoading();
        }else{
            obj.conImg = ''; obj.conText = text; obj.conVideoUrl = ''
            d.splice(c + 1, 0, obj);
            this.setData({ paraList: d }), wx.hideLoading();
        }
    },
    addText: function () {
        var i = this.data.curIndex;
        wx.navigateTo({
            url: "../edit-para/edit-para?index=" + i
        })
    },
    addImg:function(){
        var a = this, u = a.data.curIndex;
        wx.chooseImage({
            count: 9,
            sizeType: ["original", "compressed"],
            sourceType: ["album", "camera"],
            success: function (e) {
                var temp_FilePaths = JSON.stringify(e.tempFilePaths);
                wx.getNetworkType({
                    success(res) {
                        if ("none" === res.networkType) {
                            wx.showModal({
                                content: "当前网络不可用",
                                showCancel: !1,
                                confirmColor: "#2F92FF"
                            })
                        } else {
                            a.upload_img(temp_FilePaths, u);
                        }
                    }
                })
            }
        })
    },
    addVideo: function(){
        var a = this, u = a.data.curIndex;
        wx.chooseVideo({
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            compressed: true,
            camera: 'back',
            success(res) {
                var video_file_path = JSON.stringify(res.tempFilePath);
                if (res.duration > 120) {
                    wx.showModal({
                        title: "视频长度不能超过2分钟，请重新选择",
                        confirmColor: "#2F92FF",
                        showCancel: !1
                    })
                }else{
                    a.upload_video(video_file_path, u);
                }
            }
        })
    },
    editTitle: function(t){
        var e = t.currentTarget.dataset.title;
        wx.navigateTo({
            url: "../edit-title/edit-title?title=" + e
        });
    },
    changeCover: function(){
        var a = this;
        wx.chooseImage({
            count: 1,
            sizeType: ["original", "compressed"],
            sourceType: ["album", "camera"],
            success: function (r) {
                wx.showLoading({
                    title: "正在上传图片",
                    mask: !0
                });
                var e = r.tempFilePaths;
                for(let i=0;i < e.length;i++){
                    wx.uploadFile({
                        url: api.globalData.Api + '/uploadImg',
                        filePath: e[i],
                        name: "file",
                        header: { "Content-Type": "multipart/form-data" },
                        success(res) {
                            var j = JSON.parse(res.data)
                            a.dataList.coverImg[0] = j.data;
                            a.setData({
                                coverImg: a.dataList.coverImg[0]
                            }), wx.hideLoading();
                        }
                    })
                }
                
            },
            fail: function () {
                console.log("choose img fail");
            }
        });
    },
    editMusic: function () {
        this.data.SomethingTapped || (this.setData({
            SomethingTapped: !0
        }), wx.navigateTo({
            url: "../edit-music/edit-music"
        }));
    },
    editImg: function(d){
        var a = this, c = d.currentTarget.dataset.index;
        wx.chooseImage({
            count: 1,
            sizeType: ["original", "compressed"],
            sourceType: ["album", "camera"],
            success: function (r) {
                wx.showLoading({
                    title: "正在上传图片",
                    mask: !0
                });
                var e = r.tempFilePaths;
                for (let i = 0; i < e.length; i++) {
                    wx.uploadFile({
                        url: api.globalData.Api + '/uploadImg',
                        filePath: e[i],
                        name: "file",
                        header: { "Content-Type": "multipart/form-data" },
                        success(res) {
                            var j = JSON.parse(res.data),
                            p = a.data.paraList[c],
                            obj = new Object(),
                            d = a.dataList.contents;
                            if (j.status == !0){
                                if (a.dataList.coverImg.length == 0){
                                    a.dataList.coverImg[0] = j.data;
                                    a.setData({
                                        coverImg: a.dataList.coverImg[0]
                                    }), wx.hideLoading();
                                }
                                obj.conImg = j.data; obj.conText = p.conText;
                                obj.conVideoUrl = p.conVideoUrl;
                                d.splice(c, 1, obj);
                                a.setData({
                                    paraList: d,
                                    coverImg: a.dataList.coverImg[0]
                                }), wx.hideLoading();
                            }else{
                                console.log('图片上传失败')
                            }
                        }
                    })
                }

            },
            fail: function () {
                console.log("choose img fail");
            }
        });
    },
    editPara: function(e){
        var i = -2, c = e.currentTarget.dataset.context;
        this.data.ed_para_list = e.currentTarget.dataset.index;
        this.data.paraList = this.dataList.contents;
        wx.navigateTo({
            url: "../edit-para/edit-para?index=" + i + "&conText=" + c
        })
    },

    delPara: function(e){
        var a = this, i = e.currentTarget.dataset.index, u = a.dataList.contents;
        if(u.length - 1 == 0){
            wx.showModal({
                title: "至少要保留一条内容",
                confirmColor: "#2F92FF",
                showCancel: !1
            })
        }else{
            wx.showModal({
                title: "确定删除此段？",
                confirmColor: "#2F92FF",
                success: function (res) {
                    if (res.confirm) {
                        u.splice(i, 1);
                        a.setData({
                            paraList: u
                        }), a.dataList.contents = u;
                    }
                }
            });
        }
    },
    pullUp: function (a) {
        var i = a.currentTarget.dataset.index;
        if (0 !== i) {
            var e = this.dataList.contents, n = e[i];
            e[i] = e[i - 1], e[i - 1] = n;
            this.setData({
                paraList: e
            });
            this.dataList.contents = e;
        }
    },
    pullDown: function (a) {
        var i = a.currentTarget.dataset.index,
            e = this.dataList.contents;
        if (i !== e.length - 1) {
            var n = e[i];
            e[i] = e[i + 1], e[i + 1] = n;
            this.setData({
                paraList: e
            });
            this.dataList.contents = e;
        }
    },
    expandAdd: function(d){
        var a = d.currentTarget.dataset.index, i = null, e = null;
        if (this.animation = null, -1 == a ){
            this.animation = wx.createAnimation({
                duration: 150,
                timingFunction: "ease",
                transformOrigin: "0 0"
            })
        }else{
            this.animation = wx.createAnimation({
                duration: 150,
                timingFunction: "ease",
                transformOrigin: "0 100%"
            });
            //获取设备像素比
            i = d.currentTarget.offsetTop - Math.round(120 * this.dpr);
            -2 == a && (a = this.dataList.contents.length - 1, i = null, e = 260);
        }
        this.animation.scale(1, 1).step(), this.setData({
            curIndex: a,
            addPanelTop: i,
            addPanelBottom: e,
            animationData: this.animation.export()
        }), this.isCloseAddPanel = !1;
        
    },
    closeAddPanel: function () {
        this.animation = wx.createAnimation({
            duration: 150,
            timingFunction: "ease",
            transformOrigin: "0 0"
        })
        this.animation.scale(0, 0).step();
         this.setData({
            animationData: this.animation.export()
        }), this.isCloseAddPanel = !0;
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            SomethingTapped: !1
        });
        // 填充标题
        if (api.globalData.title !== undefined){
            this.dataList.titleList = api.globalData.title;
            this.setData({
                title: this.dataList.titleList
            })
        }
        // 填充音乐
        if (api.globalData.editArticleMusic !== undefined){
            this.dataList.music = api.globalData.editArticleMusic
            this.setData({
                music_name: api.globalData.editArticleMusic.music_name
            });
        }
        // 填充列表中的文字
        if (api.globalData.editArticleParaList !== undefined){
            let g = api.globalData.editArticleParaList;
            this.add_title(g, api.globalData.ed_id);
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        api.globalData.editArticleParaList = undefined
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        wx.removeStorageSync('title')
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.expandAdd({
            currentTarget: {
                dataset: {
                    index: -2
                }
            }
        });
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    createArticle: function(){

        var a = this.dataList;
        console.log(this.dataList, '所有数据');
        if (a.titleList == ''){
            wx.showModal({
                title: '提示',
                content: '请设置标题',
                showCancel: false
            })
        } else if (a.coverImg.length == 0){
            wx.showModal({
                title: '提示',
                content: '请设置封面图，个人展示的要点哟',
                showCancel: false
            })
        } else if (a.uid == ''){
            wx.showModal({
                title: '提示',
                content: '账号异常',
                showCancel: false
            })
        }else{
            if (this.data.edArticle_wy == 1){
                wx.request({
                    url: api.globalData.Api + '/articleEdit',
                    method: 'POST',
                    header: api.header,
                    dataType: 'json',
                    data: { data: JSON.stringify(a) },
                    success(res) {
                        if (res.data.status == 1) {
                            wx.showLoading({
                                title: "正在发布",
                                mask: !0
                            }), wx.redirectTo({
                                url: '../mine/mine-article?article_id=' + res.data.data + '&user_id=' + a.uid
                            });
                        }
                    }
                })
            }else{
                wx.request({
                    url: api.globalData.Api + '/articleAdd',
                    method: 'POST',
                    header: api.header,
                    dataType: 'json',
                    data: { data: JSON.stringify(a) },
                    success(res) {
                        if (res.data.status == 1) {
                            wx.showLoading({
                                title: "正在发布",
                                mask: !0
                            }), wx.redirectTo({
                                url: '../mine/mine-article?article_id=' + res.data.data + '&user_id=' + a.uid
                            });
                        }
                    }
                })
            }
            
        }
    }

})